package cn.lijigou.shopping;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;

import cn.lijigou.shopping.domain.CityTag;
import cn.lijigou.shopping.domain.MResult;
import cn.lijigou.shopping.service.LocationService;
import cn.lijigou.shopping.service.MSystem;
import cn.lijigou.shopping.util.GetSingleThreadPool;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

/**
 * @author 赵奇 E-mail:cagezhao@gmail.com
 * @version 创建时间：2012-4-6 下午04:51:03 类说明
 */

public class ChangeCityActivity extends MActivity implements OnClickListener{

	private LinearLayout layout_current_city ;
	private LinearLayout layout_refresh_city ;
	private LinearLayout title_hot_city ;
	private TextView refresh_city ;
	private LinearLayout layout_all_city ;
	private TextView city_name;
	private String from;
	private List<CityTag> mCityList = new ArrayList<CityTag>();
	private LayoutInflater mInflater;
	private ViewGroup viewGroup;
	private TextView back;
	private LinearLayout titleLeftView;
	public static Activity activity;
	private TextView title_right;
	private TextView title_center;
	private CityOnItemClick mCityOnItemClick;
	private ProgressDialog mProgress = null;
	private Timer timer;
	private ExecutorService executorService = GetSingleThreadPool.getInstance();
	
	public Handler waitHandler = new Handler(){
		
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if(msg.what == 1){
				hideProgress();
				Toast.makeText(ChangeCityActivity.this, "网络连接有异常", 1).show();
			}else if(msg.what == 2){
				hideProgress();
				setData();
			}else if(msg.what == 3){
				if(MSystem.mLocation!= null){
					if(notNull(MSystem.mLocation.getCity())){
						refresh_city.setText(MSystem.mLocation.getCity());
						refresh_city.setTextColor(Color.rgb(0, 0, 0));
						if(timer!=null){
							timer.cancel();
						}
					}
					
				}
			}
		}
	};
	
	
	protected void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.change_city);
		super.onCreate(savedInstanceState);
		overridePendingTransition(R.anim.push_in, R.anim.push_out);

		
		initView();
		setOnClickListeners();
		getHotCities();
		
		setData();
//		getCityResult();
	}


	
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		
		if(notNull(MSystem.selectCity )){
			city_name.setText(MSystem.selectCity);
			city_name.setTextColor(Color.rgb(0, 0, 0));
		}else{
			city_name.setText("请选择城市"); 
			city_name.setTextColor(Color.rgb(204, 204, 204));
		}
	}


	private void getHotCities() {
		executorService.execute(new Thread() {
			
			public void run() {
				super.run();
				if (getNetConnectState(ChangeCityActivity.this)) {
					showProgress();
					MResult mResult = MSystem.getHotCity(mCityList);
					if (mResult != null) {
						Boolean b = mResult.isSuccess();
						if (b) {
							waitHandler.sendEmptyMessage(2);
						}
					} else {
						waitHandler.sendEmptyMessage(1);
					}
				} else {
					waitHandler.sendEmptyMessage(1);
				}
			}
		});
		
	}





	private void initView() {
		from=this.getIntent().getStringExtra("from");
		activity=this;
		
		if(from.equals("welcom")){
			getCityResult();
		}
		back = (TextView) this.findViewById(R.id.title_btn_left);
		titleLeftView = (LinearLayout) this.findViewById(R.id.titleLeftView);
		back.setBackgroundResource(R.drawable.title_back_normal);

		title_right = (TextView) this.findViewById(R.id.title_btn_right);
		this.findViewById(R.id.titleRightView).setVisibility(View.GONE);
		title_right.setVisibility(View.GONE);
		title_center = (TextView) this.findViewById(R.id.text_center);
		title_center.setText("更改城市");
		
		layout_current_city = (LinearLayout) this.findViewById(R.id.layout_current_city);
		layout_refresh_city = (LinearLayout) this.findViewById(R.id.layout_refresh_city);
		title_hot_city = (LinearLayout) this.findViewById(R.id.title_hot_city);
		refresh_city = (TextView) this.findViewById(R.id.refresh_city);
		layout_all_city = (LinearLayout) this.findViewById(R.id.layout_all_city);
		city_name = (TextView) this.findViewById(R.id.city_name);
		viewGroup = (ViewGroup) this.findViewById(R.id.layout_hot_city);
		mInflater = LayoutInflater.from(ChangeCityActivity.this);
		mCityOnItemClick = new CityOnItemClick(); 
		
	}

	private void setData() {
		if(MSystem.mLocation == null){
			city_name.setText("请选择城市"); 
			city_name.setTextColor(Color.rgb(204, 204, 204));
		}else{
			if(MSystem.selectCity != null && MSystem.selectCity.equals("") ){
				city_name.setText("请选择城市");
				city_name.setTextColor(Color.rgb(0, 0, 0));
			}else{
				city_name.setText(MSystem.selectCity); 
				city_name.setTextColor(Color.rgb(0, 0, 0));
			}
//			if(notNull(MSystem.mLocation.getCity())){
//				refresh_city.setText(MSystem.mLocation.getCity());
//				refresh_city.setTextColor(Color.rgb(0, 0, 0));
//			}
		}
		if(mCityList.size() >0){
			title_hot_city.setVisibility(View.VISIBLE);
		}else{
			title_hot_city.setVisibility(View.GONE);
		}
		
		for(int i=0;i<mCityList.size();i++ ){
			LinearLayout view = (LinearLayout)mInflater.inflate(R.layout.city_item, null);
			view.setOnClickListener(mCityOnItemClick);
			if(i==0){
				view.findViewById(R.id.layout_hot_city).setBackgroundResource(R.drawable.settings_btn_midd);
			}else if(i == (mCityList.size()-1)){
				view.findViewById(R.id.layout_hot_city).setBackgroundResource(R.drawable.settings_btn_bottom);
			}
			TextView city = (TextView) view.findViewById(R.id.hot_city);
			city.setText(mCityList.get(i).getTag_name());
			view.setId(i);
			viewGroup.addView(view);
			
	   }
	}
	
	private void setOnClickListeners() {
		titleLeftView.setOnClickListener(this);
		layout_current_city.setOnClickListener(this);
		layout_refresh_city.setOnClickListener(this);
		layout_all_city.setOnClickListener(this);
	}

	public void getCityResult() {
		if (timer != null) {
			timer.cancel();
		}
		TimerTask task = new TimerTask() {
			public void run() {
				waitHandler.sendEmptyMessage(3);
			}
		};
		timer = new Timer();
		timer.schedule(task, 0, 1000);
	}

	
	public void onClick(View v) {
		MSystem.pv+=1;
		switch (v.getId()) {
		case R.id.titleLeftView:
			
			if(from.equals("home")){
				if(MSystem.mLocation==null){
					 Toast.makeText(ChangeCityActivity.this, "定位失败,请选择城市。", 1).show();
				 }
				Animation animation=AnimationUtils.loadAnimation(ChangeCityActivity.this,R.anim.home_push_rightout);
				HomeActivity.parentMainTab.mHost.getCurrentView().startAnimation(animation);
				HomeActivity.parentMainTab.mHost.setCurrentTab(0);	
				HomeActivity.parentMainTab.main_tab_home.setChecked(true);
			    Animation animations=AnimationUtils.loadAnimation(ChangeCityActivity.this,R.anim.home_push_rightin);
			    HomeActivity.parentMainTab.mHost.getCurrentView().startAnimation(animations);
				ChangeCityActivity.this.finish();
			}else{
				this.finish();
			}
			
			
			break;
		case R.id.layout_current_city:
			if(notNull(MSystem.selectCity) ){
//				Intent intent_s = new Intent(ChangeCityActivity.this, HomeActivity.class);
//				startActivity(intent_s);
//				ChangeCityActivity.this.setResult(1, intent_s);
				
				Animation animation=AnimationUtils.loadAnimation(ChangeCityActivity.this,R.anim.home_push_rightout);
				HomeActivity.parentMainTab.mHost.getCurrentView().startAnimation(animation);
				HomeActivity.parentMainTab.mHost.setCurrentTab(0);	
				HomeActivity.parentMainTab.main_tab_home.setChecked(true);
			    Animation animations=AnimationUtils.loadAnimation(ChangeCityActivity.this,R.anim.home_push_rightin);
			    HomeActivity.parentMainTab.mHost.getCurrentView().startAnimation(animations);
			    ChangeCityActivity.this.finish();
			}
			break;
		case R.id.layout_refresh_city:
			MSystem.edit+=1;
			
			//定位
			if(refresh_city.getText().equals("点击重新定位城市") ){
				 refresh_city.setText("正在定位中...");
				 refresh_city.setTextColor(Color.rgb(204, 204, 204));
				 LocationService locationService = new LocationService(ChangeCityActivity.this);
				 locationService.start();
				 getCityResult();
			}else{
				if(MSystem.mLocation != null){
					MSystem.selectCity = MSystem.mLocation.getCity();
					if(!from.equals("home")){
						if(HomeActivity.isShow = true){
							HomeActivity.isShow =false;
						}
						
					   
					}
					Animation animation=AnimationUtils.loadAnimation(ChangeCityActivity.this,R.anim.home_push_rightout);
					HomeActivity.parentMainTab.mHost.getCurrentView().startAnimation(animation);
					HomeActivity.parentMainTab.mHost.setCurrentTab(0);	
					HomeActivity.parentMainTab.main_tab_home.setChecked(true);
				    Animation animations=AnimationUtils.loadAnimation(ChangeCityActivity.this,R.anim.home_push_rightin);
				    HomeActivity.parentMainTab.mHost.getCurrentView().startAnimation(animations);
//					    else{
//						Intent mIntent  = new Intent(ChangeCityActivity.this,MainTabActivity.class);
//				        startActivity(mIntent);
//					}
					 ChangeCityActivity.this.finish();
				}
				
			}
	       
			break;
		case R.id.layout_all_city:
			Intent allCity = new Intent(this, AllCiTies.class);
			allCity.putExtra("from", from);
			
			startActivity(allCity);
			break;
		default:
			break;
		}
	}
	
	class CityOnItemClick implements OnClickListener{

		
		public void onClick(View v) {
			// TODO Auto-generated method stub
			MSystem.pv+=1;
			String city=mCityList.get(v.getId()).getTag_name();
			MSystem.selectCity =city.replace("市", "").trim() ;
			
			
			if(from.equals("home")){
				Intent intent_s = new Intent(ChangeCityActivity.this, HomeActivity.class);
				ChangeCityActivity.this.setResult(1, intent_s);
				ChangeCityActivity.this.finish();
			}else if(from.equals("today")){
				Intent intent_s = new Intent(ChangeCityActivity.this, TodayBuyActivity.class);
				ChangeCityActivity.this.setResult(1, intent_s);
			} else if(from.equals("buySite")){
				Intent intent_s = new Intent(ChangeCityActivity.this, BuySiteSortListActivity.class);
				ChangeCityActivity.this.setResult(1, intent_s);
			}else if(from.equals("welcom")){
				Intent mIntent  = new Intent(ChangeCityActivity.this,MainTabActivity.class);
		        startActivity(mIntent);
		        
			}
			Toast.makeText(ChangeCityActivity.this, "切换城市成功", 1).show();
			
			ChangeCityActivity.this.finish();
		}
		
	}
	
	
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			
			if(from.equals("home")){
				if(MSystem.mLocation==null){
					 Toast.makeText(ChangeCityActivity.this, "定位失败,请选择城市。", 1).show();
				 }
//					 Intent mIntent  = new Intent(ChangeCityActivity.this,MainTabActivity.class);
//			         startActivity(mIntent);
				
					Animation animation=AnimationUtils.loadAnimation(ChangeCityActivity.this,R.anim.home_push_rightout);
					HomeActivity.parentMainTab.mHost.getCurrentView().startAnimation(animation);
					HomeActivity.parentMainTab.mHost.setCurrentTab(0);	
					HomeActivity.parentMainTab.main_tab_home.setChecked(true);
				    Animation animations=AnimationUtils.loadAnimation(ChangeCityActivity.this,R.anim.home_push_rightin);
				    HomeActivity.parentMainTab.mHost.getCurrentView().startAnimation(animations);
					ChangeCityActivity.this.finish();
			}else{
			   ChangeCityActivity.this.finish();
			}
		}
		
		// TODO Auto-generated method stub
		return super.onKeyDown(keyCode, event);
		
	}





	public boolean getNetConnectState(Context context) {
		boolean netConnect = false;
		ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo info = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
		NetworkInfo infoM = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
		if (info.isConnected() || infoM.isConnected()) {
			netConnect = true;
		}
		return netConnect;
	}
	
	/**
	 * 显示等待框
	 */
	protected void showProgress() {
		this.runOnUiThread(new Runnable() {
			public void run() {	
				mProgress = new ProgressDialog(ChangeCityActivity.this);
				mProgress.requestWindowFeature(Window.FEATURE_NO_TITLE);
				mProgress.setMessage(ChangeCityActivity.this.getResources().getString(R.string.loading_please_wait));
				mProgress.show();
			}
		});
	}

	/**
	 * 取消等待框
	 */
	protected void hideProgress() {
		
		this.runOnUiThread(new Runnable() {
			public void run() {
				if (mProgress != null) {
					mProgress.dismiss();
				}
			}
		});
	}
	public Boolean notNull(String str){
		if(str!=null&&!str.equals("")&&str!=""&&!str.equals("null")){
			return true;
		}
		return false;
	}
}
